package com.ruoyi.web.controller.business;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.framework.web.service.AppletLoginService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.IAppletService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.impl.SysUserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName AppletController
 * @Description TODO
 * @Author ZYJ
 * @Date 2024/4/11 10:58
 * @Version 1.0
 **/
@RestController
@RequestMapping("/business/applet")
public class AppletController extends BaseController {

    @Autowired
    private IAppletService appletService;
    @Autowired
    private AppletLoginService appletLoginService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private ServerConfig serverConfig;

    /**
     * 授权登录
     * @param code
     * @param mobileCode
     * @return
     */
    @GetMapping("/weChatLogin")
    public AjaxResult weChatLogin(@RequestParam("code")String code,@RequestParam("mobileCode")String mobileCode){
        System.out.println("AppletController.authorization");
        System.out.println("code = " + code);

        Map<String,Object> map=new HashMap<>();

        //获取用户openId
        JSONObject jsonObject = appletService.getCheckByCode(code);
        System.out.println("jsonObject = " + jsonObject);

        Integer errcode = jsonObject.getInteger("errcode");
        if (errcode!=null&&errcode!=0){
            return AjaxResult.error(errcode,jsonObject.getString("errmsg"));
        }else {
            String openid = jsonObject.getString("openid");
            String sessionKey = jsonObject.getString("session_key");
            map.put("openid",openid);
            map.put("sessionKey",sessionKey);
            System.out.println("openid = " + openid);
            //检测openId所对应用户是否已存在
            SysUser userOpenId = userService.weChatOpenIdIsExists(jsonObject.getString("openid"));
            if (userOpenId!=null){
                //生成令牌
                String appletToken = appletLoginService.getAppletToken(userOpenId.getUserName(), "123456");
                map.put("token",appletToken);
            }else {
                //获取用户手机号
                String phoneNumber = appletService.getAppletUserPhone(mobileCode);

                //添加新用户
                SysUser sysUser=new SysUser();
                sysUser.setUserName(phoneNumber);
                sysUser.setNickName("微信用户");
                sysUser.setPhonenumber(phoneNumber);
                sysUser.setPassword(SecurityUtils.encryptPassword("123456"));
                sysUser.setWxOpenId(jsonObject.getString("openid"));
                //设置患者角色
                sysUser.setRoleIds(new Long[]{101L});
                userService.insertUser(sysUser);

                //生成令牌
                String appletToken = appletLoginService.getAppletToken(sysUser.getUserName(), "123456");
                map.put("token",appletToken);
            }
        }
        return AjaxResult.success(map);
    }


    /**
     * 完善信息
     * @param user
     * @return
     */
    @PostMapping("/perfectUserInfo")
    public AjaxResult perfectUserInfo(@RequestBody SysUser user){
        System.out.println("user = " + user);
        Long userId = SecurityUtils.getUserId();
        user.setUserId(userId);
        return AjaxResult.success(userService.perfectUserInfo(user));
    }

    /**
     * 获取用户信息
     * @return
     */
    @GetMapping("/getUserInfo")
    public AjaxResult getUserInfo(){
        Long userId = SecurityUtils.getUserId();
        Map<String, Object> userInfo = userService.getUserInfo(userId);
        return AjaxResult.success(userInfo);
    }

    /**
     * 医师端小程序登录
     * @param loginBody
     * @return
     */
    @PostMapping("/appletDoctorLogin")
    public AjaxResult login(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = appletLoginService.getAppletToken(loginBody.getUsername(), loginBody.getPassword());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 医师端修改密码
     * @return
     */
    @PostMapping("/updatePwd")
    public AjaxResult updatePwd(@RequestBody Map<String,String> passMap)
    {
        String oldPassword = passMap.get("oldPassword");
        String newPassword = passMap.get("newPassword");

        LoginUser loginUser = getLoginUser();
        String userName = loginUser.getUsername();
        String password = loginUser.getPassword();
        if (!SecurityUtils.matchesPassword(oldPassword, password))
        {
            return error("修改密码失败，旧密码错误");
        }
        if (SecurityUtils.matchesPassword(newPassword, password))
        {
            return error("新密码不能与旧密码相同");
        }
        newPassword = SecurityUtils.encryptPassword(newPassword);
        if (userService.resetUserPwd(userName, newPassword) > 0)
        {
            // 更新缓存用户密码
            loginUser.getUser().setPassword(newPassword);
            tokenService.setLoginUser(loginUser);
            return success();
        }
        return error("修改密码异常，请联系管理员");
    }

    /**
     * 获取当前登录用户id
     * @return
     */
    @GetMapping("/getLoginUserId")
    public AjaxResult getLoginUserId(){
        Long userId = SecurityUtils.getUserId();
        String avatar = userService.getAvatarByUserId(userId);
        Map<String,Object>map=new HashMap<>();
        map.put("userId",userId);
        map.put("avatar",serverConfig.getUrl()+"/prod-api"+avatar);
        return AjaxResult.success(map);
    }
}
